# 抢票系统.
# 1. 先可以查票.查询余票数.  并发
# 2. 进行购买,向服务端发送请求,服务端接收请求,在后端将票数-1,返回到前端. 串行.

# from multiprocessing import Process
# import json
# import time
# import os
# import random
#
#
# def search():
#     time.sleep(random.randint(1,3))  # 模拟网络延迟(查询环节)
#     with open('ticket.json',encoding='utf-8') as f1:
#         dic = json.load(f1)
#         print(f'{os.getpid()} 查看了票数,剩余{dic["count"]}')
#
#
# def paid():
#     with open('ticket.json', encoding='utf-8') as f1:
#         dic = json.load(f1)
#     if dic['count'] > 0:
#         dic['count'] -= 1
#         time.sleep(random.randint(1,3))  # 模拟网络延迟(购买环节)
#         with open('ticket.json', encoding='utf-8',mode='w') as f1:
#             json.dump(dic,f1)
#         print(f'{os.getpid()} 购买成功')
#
# def task():
#     search()
#     paid()
#
#
# if __name__ == '__main__':
#
#     for i in range(6):
#         p = Process(target=task)
#         p.start()

# 当多个进程共强一个数据时,如果要保证数据的安全,必须要串行.
# 要想让购买环节进行串行,我们必须要加锁处理.

#
# from multiprocessing import Process
# from multiprocessing import Lock
# import json
# import time
# import os
# import random
#
#
# def search():
#     time.sleep(random.randint(1,3))  # 模拟网络延迟(查询环节)
#     with open('ticket.json',encoding='utf-8') as f1:
#         dic = json.load(f1)
#         print(f'{os.getpid()} 查看了票数,剩余{dic["count"]}')
#
#
# def paid():
#     with open('ticket.json', encoding='utf-8') as f1:
#
#         dic = json.load(f1)
#     if dic['count'] > 0:
#         dic['count'] -= 1
#         time.sleep(random.randint(1,3))  # 模拟网络延迟(购买环节)
#         with open('ticket.json', encoding='utf-8',mode='w') as f1:
#             json.dump(dic,f1)
#         print(f'{os.getpid()} 购买成功')
#
#
# def task(lock):
#     search()
#     lock.acquire()
#     paid()
#     lock.release()
#
# if __name__ == '__main__':
#     mutex = Lock()
#     for i in range(6):
#         p = Process(target=task,args=(mutex,))
#         p.start()


# 当很多进程共强一个资源(数据)时, 你要保证顺序(数据的安全),一定要串行.
# 互斥锁: 可以公平性的保证顺序以及数据的安全.

# 基于文件的进程之间的通信:
    # 效率低.
    # 自己加锁麻烦而且很容易出现死锁.

# dic = {'name': 'alex'}
# import json
# print(json.dumps(dic))
